// table
!(function ($) {
    var filterParams = {};

    var BeesTable = function (target, options) {
        this.target = $(target);
        this.options = options;
        this.bt = null;
    };

    BeesTable.prototype.updateQueryParams = function (args) {
        $.extend(true, filterParams, args);
    };

    BeesTable.prototype.init = function () {
        // 默认设置表格内容居中
        this.options.columns && this.options.columns.forEach(function (item) {
            if (!item.align) {
                item.align = 'center';
                item.valign = 'middle'
            }
        });


        // 默认表格配置
        var defaults = {
            url: '',		    //请求地址
            method: "get",    //ajax方式,post还是get
            ajaxOptions: {				    //ajax请求的附带参数
                data: this.options.params || {}
            },
            columns: this.options.columns || [], // 列数组

            classes: 'table table-striped table-bordered table-hover',
            locale: 'zh-CN',
            contentType: "application/x-www-form-urlencoded",
            clickToSelect: true,	    //是否启用点击选中行
            singleSelect: false,        //设置true为允许复选框仅选择一行
            maintainSelected: false,    //分页仍然选中
            striped: true,              //是否显示行间隔色
            toolbar: undefined,         //顶部工具条
            cache: false,               //是否使用缓存,默认为true
            sortable: true,             //是否启用排序
            sortOrder: "desc",          //排序方式
            pagination: true,           //是否启用分页
            pageNumber: parseInt($.cookie("curAgentTablePageNumber") ? $.cookie("curAgentTablePageNumber") : 1),  //初始化加载第一页，默认第一页
            pageSize: 12,      			//每页的记录行数
            pageList: [],  	            //可供选择的每页的行数
            queryParamsType: 'limit', 	//默认值为 'limit' ,在默认情况下 传给服务端的参数为：offset,limit,sort
            sidePagination: 'server',   //分页方式：client客户端分页，server服务端分页（*）

            undefinedText: '',              // 定义默认undefined文本
            showColumns: false,             // 是否显示所有的列
            showRefresh: false,             // 是否显示刷新按钮
            search: false,                  // 默认关闭搜索
            searchAlign: 'left',            // 默认搜索框靠左
            searchOnEnterKey: true,         // 默认开启回车搜索
            searchText: '',                 // 搜索框默认填充内容，默认为空
            showToggle: false,              // 默认关闭切换展示方式按钮
            showExport: false,              // 是否打开下载， 默认关闭
            exportDataType: 'all',          // 下载范围 support: 'basic', 'all', 'selected'. 默认all
            exportTypes: ['csv','excel'],   // 下载类型， support types: 'json', 'xml', 'png', 'csv', 'txt', 'sql', 'doc', 'excel', 'xlsx'. 默认 ['csv','excel']

            queryParams: function (params) {
                $.extend(true, params, filterParams);
                return params;
            },
            responseHandler: function(res){
                if(res.code == 403){
                    if(res.data.type == 'login'){
                        window.location.href = '/users/login/';
                    }else {
                        bees.tipError({
                            message: res.data.message
                        });
                        return {
                            "total": 0,
                            "rows": null
                        }
                    }
                }
                else if(res.code == 500){
                    bees.tipError({
                        message: res.data.message
                    });
                    return {
                        "total": 0,
                        "rows": null
                    }
                }
                else {
                    return {
                        "total": res.data.total,
                        "rows": res.data.rows
                    }
                }
            },
            onPageChange: function (pageNumber) {
                $.cookie("curAgentTablePageNumber", pageNumber);
            }
        };

        if (this.options.fixedHeader) {
            var clientHeight = $(target)[0].offsetParent.clientHeight;
            var offsetTop = $(target)[0].offsetTop;
            defaults.height = clientHeight - offsetTop;
        }

        // 合并自定义参数
        $.extend(true, defaults, this.options);
        
        // bootstrap-table表格渲染方法调用
        // this.bt = this.target.bootstrapTable('destroy').bootstrapTable(defaults);
        this.bt = this.target.bootstrapTable(defaults);
    };

    BeesTable.prototype.search = function (args) {
        this.updateQueryParams(args);
        this.bt.bootstrapTable('filterBy');
    };

    // BeesTable.prototype.refresh = function () {
    //     this.bt.bootstrapTable('refresh');
    // };

    BeesTable.prototype.getFilterParams = function () {
        return filterParams;
    };

    // ========================

    $.fn.beesTable = function(option) {
        // 保证每次点击列表页面重新计算当前页
        // $.removeCookie("curAgentTablePageNumber");

        var args = [];
        if(arguments.length > 1){
            args = Array.prototype.slice.apply(arguments, [1, ]);
        }

        var instance = null;
        var returnValue;
        this.each(function(index, ele) {
            instance = $(ele).data('bees.table');

            // string
            if (typeof option === 'string') {
                if(instance) {
                    returnValue = instance[option].apply(instance, args);
                }else {
                    console.error("Initialize the BootstrapTable first is required")
                }
            }
            // object
            else {
                var options = typeof option == 'object' && option;
                if(!instance) $(ele).data('bees.table', (instance = new BeesTable(this, options)));
                instance.init();
            }
        });

        return typeof returnValue === 'undefined' ? instance : returnValue;
    };

    $.fn.beesTable.Constructor = BeesTable;

    $.fn.beesTable.defaultFilterParams = function (args) {
        $.extend(true, filterParams, args);
    };

})(window.jQuery);


!(function ($) {
    var Bees = {

        // defaultPK
        defaultPK: '00000000-0000-0000-0000-000000000000',

        // 初始化select2
        initSelect2: function (options) {
            var defaults = {
                ele: $('.select2'),
                language: "zh-CN",
                maximumInputLength: 20,      //允许搜索长度
                minimumResultsForSearch: 10,  //至少20个结果的时候显示搜索
                allowClear: true
            };
            $.extend(true, defaults, options);

            var $ele = defaults.ele;
            delete defaults.ele;
            $ele.select2(defaults);
        },

        // 初始化服务器端select2
        initServerSideSelect2: function(target, params, options){
            var url = params.url;
            var selected = params.selected;

            var defaults = {
                language: "zh-CN",  // 设置提示语言
                delay: 250,        // 延迟显示
                maximumInputLength: 20,       //允许搜索长度
                minimumResultsForSearch: 10,  //至少10个结果的时候显示搜索
                allowClear: true,
                ajax: {
                    url: url,
                    type: 'get',
                    dataType: 'json',
                    data: function (params) {
                        var query = {
                            search: params.term,
                            page: params.page || 1,
                            type: 'select2',
                            filter: null
                        };
                        // Query parameters will be ?search=[term]&page=[page]
                        return query;
                    },
                    processResults: function (result, params) {
                        params.page = params.page || 1;
                        var items = $.map(result.data.rows, function (obj) {
                            var item = {};
                            item.id = obj.id || obj.pk;
                            item.text = obj.name || obj.text || obj.hostname;
                            return item;
                        });

                        return {
                            results: items,
                            pagination: {
                                more: (params.page * 10) < result.data.total
                            }
                        };
                    }
                }
            };
            $.extend(true, defaults, options);
            target.select2(defaults);

            // 数据回显
            if(selected){
                $.ajax({
                    type: 'get',
                    url: url,
                    data: {
                        type: 'select2',
                        page: null,
                        filter: selected
                    }
                }).then(function (result) {
                    var items = $.map(result.data.rows, function (obj) {
                        var item = {};
                        item.id = obj.id || obj.pk;
                        item.text = obj.name || obj.text || obj.hostname;
                        return item;
                    });

                    var options = [];
                    $.each(items, function(index, obj){
                        var option = new Option(obj.text, obj.id, true, true);
                        options.push(option);
                    });

                    target.append(options).trigger('change');
                });
            }
        },

        // select2数据回显
        select2DataEcho: function (target, params) {
            var url = params.url;
            var selected = params.selected;
            var async = params.async;

            $.ajax({
                async: async,
                url: url,
                type: 'get'
            }).done(function (result) {

                var items = $.map(result.data.rows, function (obj) {
                    var item = {};
                    item.id = obj.id || obj.pk;
                    item.text = obj.name || obj.text;
                    return item;
                });

                var options = [];
                $.each(items, function(index, obj){
                    if($.inArray(obj.id, selected) >= 0){
                        var option = new Option(obj.text, obj.id, true, true);
                        options.push(option);
                    }
                });

                target.append(options).trigger('change');
            });
        },

        // 验证插件
        niceValidate: function (target, options) {
            var defaults = {
                msgMaker: false,
                invalid: function (form, errors) {
                    bees.tipError({
                        message: errors[0]
                    })
                },
                invalidClass: 'has-error'
            };
            $.extend(true, defaults, options);
            target.validator(defaults)
        },

        // 初始化日器插件
        initDaterangepicker: function(target, options){
            var defaults = {
                opens:'left',
                showDropdowns: true,    // 是否显示下拉框选择年和月
                timePicker: true,
                timePickerSeconds: true,
                timePicker24Hour: true,
                singleDatePicker: false,
                startDate:moment().startOf('hour').subtract(365, 'day'),
                endDate:moment().startOf('hour').add(1, 'hour'),
                minYear: 1990,
                maxSpan: {
                    "days": 3650
                },
                locale: {
                    format: 'YYYY-MM-DD H:mm:ss',
                    separator: ' ~ ',
                    applyLabel: '确定',
                    cancelLabel: '取消',
                    weekLabel: 'W',
                    customRangeLabel: '自定义',
                    daysOfWeek: [ '日', '一', '二', '三', '四', '五', '六' ],
                    monthNames: [ '一月', '二月', '三月', '四月', '五月', '六月','七月', '八月', '九月', '十月', '十一月', '十二月' ],
                    firstDay: 1
                }
            };

            $.extend(true, defaults, options);

            target.daterangepicker(defaults);

            target.on('renderCalendarComplete.daterangepicker', function(event, picker) {
                $(".monthselect,.yearselect").select2(
                    {
                        minimumResultsForSearch: -1,
                        dropdownCssClass: 'dateselect-dropdown'
                    }
                );
            });

            target.on('renderTimePickerComplete.daterangepicker', function(event, picker) {
                var initSelector = "";
                if(defaults.timePicker){
                    initSelector += ".hourselect,.minuteselect";
                }
                if (defaults.timePickerSeconds){
                    initSelector += ",.secondselect"
                }
                if(!defaults.timePicker24Hour){
                    initSelector += ",.ampmselect"
                }

                if (initSelector) {
                    $(initSelector).select2(
                        {
                            minimumResultsForSearch: -1,
                            dropdownCssClass: 'timeselect-dropdown'
                        }
                    );
                }
            });

        },

        // 初始化权限菜单树(基于treeview)
        initMenuTree: function (target, options, selected) {
            // 显示选择的节点
            function processNodeData(node) {
                var selectOption = '<option value="'+node.id+'">'+node.text+'</option>';
                $('.menu-select > select').children('option').remove();
                $('.menu-select > select').append(selectOption);

                var node = "<span style='color: #666'>" + node.text + "</span>";
                $('.menu-select > span').removeClass('collapse').addClass('expand').html(node);
                $('.menu-tree').hide();
            }

            // 回显选择的节点
            function showSelectNode(node, selected) {
                if ($.inArray(node.id, selected) >= 0){
                    processNodeData(node);
                }

                if (node.nodes !== undefined){
                    $.each(node.nodes, function (index, node) {
                        showSelectNode(node, selected);
                    })
                }
            }

            var defaults = {
                data: [],
                icon: "fa",
                collapseIcon: "fa fa-caret-down",
                expandIcon: "fa fa-caret-right",
                showBorder: false,
                selectable: true,
                onhoverColor: "#25476A",
                selectedBackColor: "#25476A",
                highlightSelected: true,
                state: {
                    checked: false,
                    disabled: true,
                    expanded: true,
                    selected: true
                },
                levels: 2,  //默认展开的级别
                tags: ['available'],
                onNodeSelected: function (event, node) {
                    processNodeData(node);
                }
            };
            $.extend(true, defaults, options);

            // 处理回显
            if (selected){
                $.each(options.data, function (index, node) {
                    showSelectNode(node, selected);
                });
            }

            // 初始化
            target.treeview(defaults);

            // 点击文本框显示下列菜单框
            $('.menu-select > span').on("click", function (e) {
                e.stopPropagation();
                $('.menu-tree').show();
                $('.menu-select > span').removeClass('expand').addClass('collapse');
            });

            // 点击空白处隐藏菜单
            $(document).on('click', function (e) {
                // 阻止menu-tree中的点击图标的默认事件被冒泡到这里
                var $target = $(e.target);
                if($target.hasClass("icon")){
                    return
                }
                // 隐藏菜单树
                if($('.menu-tree').css('display') === 'block'){
                    $('.menu-tree').hide();
                }
            })

        },

        // 初始化角色菜单树(基于treeview)
        initRoleTree: function(target, options, selected){
            var nodeCheckedSilent = false;
            function nodeChecked(event, node) {
                if (nodeCheckedSilent) {
                    return;
                }
                nodeCheckedSilent = true;
                checkAllParent(node);
                checkAllSon(node);
                nodeCheckedSilent = false;
            }

            var nodeUncheckedSilent = false;
            function nodeUnchecked(event, node) {
                if (nodeUncheckedSilent)
                    return;
                nodeUncheckedSilent = true;
                uncheckAllParent(node);
                uncheckAllSon(node);
                nodeUncheckedSilent = false;
            }

            //选中全部父节点
            function checkAllParent(node) {
                // checkNode: 选择指定的节点，接收节点或节点ID。
                target.treeview('checkNode', node.nodeId, {
                    silent: true    // 传入silent来阻止其它事件
                });
                var parentNode = target.treeview('getParent', node.nodeId);
                if (!("nodeId" in parentNode)) {
                    return;
                } else {
                    checkAllParent(parentNode);
                }
            }
            //取消全部父节点
            function uncheckAllParent(node) {
                target.treeview('uncheckNode', node.nodeId, {
                    silent: true
                });
                var siblings = target.treeview('getSiblings', node.nodeId);
                var parentNode = target.treeview('getParent', node.nodeId);
                if (!("nodeId" in parentNode)) {
                    return;
                }
                var isAllUnchecked = true; //是否全部没选中
                for (var i in siblings) {
                    if (siblings[i].state.checked) {
                        isAllUnchecked = false;
                        break;
                    }
                }
                if (isAllUnchecked) {
                    uncheckAllParent(parentNode);
                }

            }

            //级联选中所有子节点
            function checkAllSon(node) {
                target.treeview('checkNode', node.nodeId, {
                    silent: true
                });
                if (node.nodes != null && node.nodes.length > 0) {
                    for (var i in node.nodes) {
                        checkAllSon(node.nodes[i]);
                    }
                }
            }
            //级联取消所有子节点
            function uncheckAllSon(node) {
                target.treeview('uncheckNode', node.nodeId, {
                    silent: true
                });
                if (node.nodes != null && node.nodes.length > 0) {
                    for (var i in node.nodes) {
                        uncheckAllSon(node.nodes[i]);
                    }
                }
            }
            
            // 选中选择的节点
            function selectCheckNode(node, selected) {
                if ($.inArray(node.id, selected) >= 0){
                    node['state'] = {'checked': true};
                }else{
                    node['state'] = {'checked': false};
                }

                if (node.nodes !== undefined){
                    $.each(node.nodes, function (index, node) {
                        selectCheckNode(node, selected);
                    })
                }
            }
            // 在options.data中增加节点的选中状态
            if(selected){
                $.each(options.data, function (index, node) {
                    selectCheckNode(node, selected);
                });
            }

            var defaults = {
                data: [],
                emptyIcon: "icon-none",
                collapseIcon: "fa fa-caret-down fa-lg",
                expandIcon: "fa fa-caret-right fa-lg",
                checkedIcon: "fa fa-check-square fa-lg",
                uncheckedIcon: "fa fa-square-o fa-lg",
                showIcon: true,
                showCheckbox: true,
                showBorder: false,

                selectable: false,
                highlightSelected: false,
                onhoverColor: "#FFF",
                selectedBackColor: "#FFF",
                state: {
                    checked: true,
                    disabled: true,
                    expanded: true,
                    selected: false
                },
                levels: 3,  //默认展开的级别
                tags: ['available'],

                onNodeChecked: nodeChecked,
                onNodeUnchecked: nodeUnchecked
            };
            $.extend(true, defaults, options);

            // 初始化
            target.treeview(defaults);

            // 单击LI也能展开和折叠
            target.on('click', 'li', function (e) {
                // console.log('$target[0].nodeName ===>', $(e.target)[0].nodeName );
                if($(e.target)[0].nodeName === "SPAN"){
                    return
                }

                //找到当前节点id
                var nodeId = $(this).data('nodeid');
                //获取当前节点对象
                var node = target.treeview('getNode', nodeId);

                if (node.state.expanded) {
                    //处于展开状态则折叠
                    target.treeview('collapseNode', node.nodeId, { silent: true });
                } else {
                    //展开
                    target.treeview('expandNode', node.nodeId, { silent: true });
                }
            });
        },

        // 初始化节点菜单树(基于treeview)
        initNodeTree: function (target, options, selected) {
            
            var nodes = [];

            var processNodeData = function () {
                // 处理select2
                var options = [];
                $.each(nodes, function (i, n) {
                    options.push('<option value="'+n.id+'">'+n.text+'</option>');
                });
                $('.menu-select > select').children('option').remove();
                $('.menu-select > select').append(options);

                // 处理显示文本
                var nodeTexts = [];
                $.each(nodes, function (i, n) {
                    var style = "" +
                        "color: #fff; " +
                        "background-color: #25476a; " +
                        "border: 1px solid #25476a !important; " +
                        "padding: 2px 5px; " +
                        "margin-right: 5px;" +
                        "border-radius: 3px;";
                    nodeTexts.push("<span style='"+style+"'><icon style='font-weight: 700'>× </icon>" + n.text + "</span>");
                });
                $('.menu-select > span').removeClass('collapse').addClass('expand').html(nodeTexts);
                $('.menu-tree').hide();
            };

            var deleteNode = function(e) {
                var text = $(e.target).parent().text().replace('× ', '');
                $.each(nodes, function (i, n) {
                    if(n.text == text){
                        nodes.splice(i,1);
                    }
                });
                processNodeData();
            };

            var defaults = {
                data: [],
                icon: "fa",
                collapseIcon: "fa fa-caret-down",
                expandIcon: "fa fa-caret-right",
                showBorder: false,
                selectable: true,
                onhoverColor: "#25476A",
                selectedBackColor: "#25476A",
                highlightSelected: true,
                state: {
                    checked: false,
                    disabled: true,
                    expanded: true,
                    selected: true
                },
                levels: 3,  //默认展开的级别
                tags: ['available'],
                onNodeSelected: function (event, node) {
                    var nodeIds = [];
                    $.each(nodes, function (i, n) {
                        nodeIds.push(n.id);
                    });
                    if($.inArray(node.id, nodeIds) < 0 ){
                        nodes.push(node);
                    }
                    //处理数据
                    processNodeData();
                }
            };
            $.extend(true, defaults, options);

            // 初始化
            target.treeview(defaults);

            if(selected){
                nodes = selected;
                processNodeData()
            }

            // 点击文本框显示下列菜单框
            $('.menu-select > span').on("click", function (e) {
                e.stopPropagation();
                if(e.target.nodeName == 'ICON'){
                    // 删除节点
                    deleteNode(e);
                    return;
                }

                $('.menu-tree').show();
                $('.menu-select > span').removeClass('expand').addClass('collapse');
            });

            // 点击空白处隐藏菜单
            $(document).on('click', function (e) {
                // 阻止menu-tree中的点击图标的默认事件被冒泡到这里
                var $target = $(e.target);
                if($target.hasClass("icon")){
                    return
                }
                // 隐藏菜单树
                if($('.menu-tree').css('display') === 'block'){
                    $('.menu-tree').hide();
                }
            })
        },

        // 用户消息提示
        tipInfo: function (options) {
            var defaults = {
                type: 'info',
                icon : 'fa fa-info-circle icon-2x',
                message : '',
                container : 'floating',
                floating: {
                    position: 'top-center'
                },
                timer : 1500
            };
            $.extend(true, defaults, options);
            $.niftyNoty(defaults);
        },
        tipWaring: function (options) {
            var defaults = {
                type: 'warning',
                icon : 'fa fa-warning icon-2x',
                message : '',
                container : 'floating',
                floating: {
                    position: 'top-center'
                },
                timer : 1500
            };
            $.extend(true, defaults, options);
            $.niftyNoty(defaults);
        },
        tipSuccess: function (options) {
            var defaults = {
                type: 'success',
                icon : 'fa fa-check icon-2x',
                message : '',
                container : 'floating',
                floating: {
                    position: 'top-center'
                },
                timer : 1500
            };
            $.extend(true, defaults, options);
            $.niftyNoty(defaults);
        },
        tipError: function (options) {
            var defaults = {
                type: 'danger',
                icon : 'fa fa-exclamation-circle icon-2x',
                message : '',
                container : 'floating',
                floating: {
                    position: 'top-center'
                },
                timer : 1500
            };
            $.extend(true, defaults, options);
            $.niftyNoty(defaults);
        },

        // 提示确认框
        confirmBox: function (options) {
            if (typeof bootbox === 'undefined'){
                throw new Error('Bootbox\'s JavaScript requires jQuery');
            }

            var defaults = {
                title: options.title,
                content: options.content,
                confirmCallback: function () {
                },
                cancelCallback: function () {
                }
            };
            $.extend(true, defaults, options);
            bootbox.confirm({
                locale: "zh_CN",
                size: "small",
                message : "<p class='text-semibold text-main'>"+defaults.title+"</p><p style='margin: 0;'>"+defaults.content+"</p>",
                buttons: {
                    cancel: {
                        label: "取消"
                    },
                    confirm: {
                        label: "确定"
                    }
                },
                callback : function(result) {
                    if(result){
                        defaults.confirmCallback();
                    }else {
                        defaults.cancelCallback();
                    }
                }
            });
        },

        // 绑定表格操作CRUD
        bindTableOperator: function (options) {
            var defaults = {
                table: 'element',
                operator: {
                    add: {
                        disable: false,
                        ele: $('#add'),
                        msg: undefined,
                        href: "#",
                        isTransferParams: false
                    },
                    show: {
                        disable: false,
                        ele: $('#show'),
                        msg: "请选择需要查看的行",
                        href: "#"
                    },
                    edit: {
                        disable: false,
                        ele: $('#edit'),
                        msg: "请选择需要修改的行",
                        href: "#"
                    },
                    del: {
                        disable: false,
                        ele: $('#del'),
                        msg: "请选择需要删除的行",
                        href: undefined,
                        confirmCallback: function () {}
                    }
                }
            };
            $.extend(true, defaults, options);

            var $table = defaults.table;
            $.each(defaults.operator, function (method, params) {
                if(!params.disable){
                    params.ele.on('click', function () {
                        // 获取选择的数据
                        var rows = $table.bootstrapTable('getSelections');
                        var data = rows[0];
                        var count = rows.length;
                        // 没有选择对应的行
                        if(!count){
                            if(method === 'add') {
                                window.location.href = params.href
                            }else {
                                bees.tipWaring({
                                    message: params.msg
                                });
                            }
                        }
                        // 选择了对应的行
                        else {
                            // del
                            if(method === 'del'){
                                // 显示删除确定对话框
                                bees.confirmBox({
                                    title: '删除确认',
                                    content: '您确定要删除选中的行吗？',
                                    confirmCallback: function () {
                                        params.confirmCallback(data);
                                    }
                                })
                            }
                            // edit
                            else if(method === 'edit'){
                                // 编辑之前,保存过滤的数据
                                var filterParams = $table.beesTable("getFilterParams");
                                window.sessionStorage.setItem("filterParams", JSON.stringify(filterParams));
                                // 跳转到编辑页面
                                window.location.href = params.href.replace(bees.defaultPK, data.id);
                            }
                            // show
                            else if(method === 'show'){
                                // 查看之前,保存过滤的数据
                                var filterParams = $table.beesTable("getFilterParams");
                                window.sessionStorage.setItem("filterParams", JSON.stringify(filterParams));
                                // 跳转到查看页面
                                window.location.href = params.href.replace(bees.defaultPK, data.id);
                            }
                            // add
                            else if(method === 'add'){
                                if(params.isTransferParams){
                                    window.location.href = params.href+'?pk='+data.id;
                                }else {
                                    window.location.href = params.href;
                                }
                            }
                            // other
                            else {
                                // 跳转到页面
                                window.location.href = params.href.replace(bees.defaultPK, data.id);
                            }
                        }
                    });
                }else{
                    console.info('方法'+method+'没有被激活')
                }
            })
        },

        // 绑定表格搜索
        bindTableSearch: function (options) {
            var defaults = {
                table: 'element',
                searches: []
            };
            $.extend(true, defaults, options);

            var $table = defaults.table;
            $.each(defaults.searches, function (index, search) {
                var eventType = search.eventType;
                var eventSource = search.eventSource;
                var dataCallback = search.data;

                eventSource.on(eventType, function () {
                    var data = dataCallback();
                    $table.beesTable("search", data);
                })
            })
        },

        // 获取URL查询参数
        getQueryVariable: function(variable) {
           var query = window.location.search.substring(1);
           var vars = query.split("&");
           for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){
                   return pair[1];
               }
           }
           return false;
        },

        // 获取访问的URL
        getAccessUrl: function () {
            var url = document.location.toString();
            var arrUrl = url.split("//");
            var start = arrUrl[1].indexOf("/");
            var accessUrl = arrUrl[1].substring(start);
            return accessUrl;
        },

        // FormDataArray转object
        serializeToObject: function (jsonArray){
            var o = {};
            $.each(jsonArray, function() {
                if (o[this.name] !== undefined) {
                    // if (!o[this.name].push) {
                    //     o[this.name] = [o[this.name]];
                    // }
                    // o[this.name].push(this.value || '');
                    o[this.name] = o[this.name] + ',' + this.value
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        },

        // 滚动到当前菜单
        scrollToMenuNav: function (ele) {
            var $target = $(ele).closest('.nano');
            $target.nanoScroller({ scrollTo: $(ele) });
        },

        // 激活导航
        activeMenuNav: function (ele) {
            $(ele).addClass('active-link').siblings('li').removeClass('active-link');
            $(ele).parent('ul').addClass('collapse in').parent('li').addClass('active-sub');

            // 三级菜单
            $(ele).parent('ul').parent('li').siblings('li').removeClass('active-sub');
            $(ele).parent('ul').parent('li').parent('ul').addClass('collapse in');

            // 移动滚动条
            bees.scrollToMenuNav(ele);
        },

        // 初始化导航
        initMenuNav: function () {
            var accessOriginalUrl = bees.getAccessUrl();
            if (accessOriginalUrl.indexOf("?") != -1) {
                accessOriginalUrl = accessOriginalUrl.split("?")[0];
            }

            // 特殊url处理(需要手动激活导航)
            var selfActiveNavURL = ['/terminal/session', '/terminal/log', '/users/log', '/tasks/log'];
            for(var i=0; i<selfActiveNavURL.length; i++){
                if(accessOriginalUrl.startsWith(selfActiveNavURL[i])){
                    return false
                }
            }

            // 固定url处理
            var menus = $('#mainnav-menu li');
            menus.each(function (index, menu) {
                var menuOriginalUrl = $(menu).find('a').attr('href');
                if(menuOriginalUrl){
                    var menuUrl = menuOriginalUrl.split("/").slice(0, 3).join("/");
                    var accessUrl = accessOriginalUrl.split("/").slice(0, 3).join("/");
                    // console.log(menuUrl, '==' , accessUrl, '-->' , accessUrl == menuUrl);
                    if(accessUrl == menuUrl){
                        bees.activeMenuNav(menu);
                        return false;
                    }
                }
            });
        },
        
        // 文本截取显示省略号
        showText: function (text, numSub) {
            if(text == null){
                return "";
            }
            if(text.length > numSub){
                return text.substring(0, numSub - 1) + "...";
            }
            return text;
        },

        // 可变参考操作
        initVariableParameterOperator: function () {
            $(".args").on('click', '.icon-plus', function () {
                var template = '<div class="row item">' +
                    '<div class="col-lg-10">' +
                        '<input name="args" type="text" class="form-control value" placeholder="值" autocomplete="off">' +
                    '</div>' +
                    '<div class="col-lg-2">' +
                        '<span class="icon icon-minus"><i class="fa fa-minus" aria-hidden="true"></i></span>' +
                    '</div>' +
                '</div>';
                $(".args").append(template);
            }).on('click', '.icon-minus',  function () {
                $(this).closest('.item').remove();
            });

            $(".kwargs").on('click', '.icon-plus', function () {
                var template = '<div class="row item">' +
                    '<div class="col-lg-5">' +
                        '<input name="key" type="text" class="form-control key" placeholder="键" autocomplete="off">' +
                    '</div>' +
                    '<div class="col-lg-5">' +
                        '<input name="value" type="text" class="form-control value" placeholder="值" autocomplete="off">' +
                    '</div>' +
                    '<div class="col-lg-2">' +
                        '<span class="icon icon-minus"><i class="fa fa-minus" aria-hidden="true"></i></span>' +
                    '</div>' +
                '</div>';
                $(".kwargs").append(template);
            }).on('click', '.icon-minus',  function () {
                $(this).closest('.item').remove();
            });
        },

        // 睡眠
        sleep: function(time) {
            var startTime = new Date().getTime() + parseInt(time, 10);
            while(new Date().getTime() < startTime) {}
        }
    };

    window.bees = Bees;

})(window.jQuery);


// 激活导航左侧导航菜单
!(function($){
    bees.initMenuNav();
})(window.jQuery);
